package com.ygnn.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.ygnn.common.Pojo.Users;
import com.ygnn.config.WxInformation;
import com.ygnn.mapper.UserMapper;
import com.ygnn.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.http.HttpUtil;



@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
     private WxInformation wxInformation;


    /**
     * 登录
     *
     * @param code
     * @return
     */
    @Override
    @Transactional
    public Users login(String code ) {
        //code获取openid  定义请求地址,替换参数
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                +wxInformation.getPublicAppid()+"&secret="+wxInformation.getPublicAppsecret()+
                "&code="+code+"&grant_type=authorization_code";
        //发送请求 的到返回结果
        String token = HttpUtil.get(url);
        //先把String对象转换成json对象
        JSONObject tokenobj= JSONObject.parseObject(token);
        String openId= (String) tokenobj.get("openid");;
        log.info("用户登录注册:{}",openId);
        if(openId==null){
            return null;
        }
        Users user = userMapper.selectByOpenId(openId);
        //第一次登录
        if(user==null){
            //添加到用户表
            Users users = new Users();
            users.setOpenid(openId);
            userMapper.save(users);
//           activityRecordService.CouponInsert(4,openId);
            return users;
        }
        //数据库已有数据
        return user;

    }

}




